import datetime
import os
from flask import Flask, render_template, request, redirect, url_for
from concurrent.futures.thread import ThreadPoolExecutor
from main import run_like, run_metoo
from cache import cache


pool = ThreadPoolExecutor(2)


app = Flask(__name__)


@app.route('/')
def index():
    ip_pool = cache.get('ip_pool') or ''
    return render_template('config.html', address='', ID='', times='', ip_pool=ip_pool)


@app.route('/metoo')
def metoo():
    ip_pool = cache.get('ip_pool') or ''
    return render_template('metoo.html', address='', ID='', times='', ip_pool=ip_pool)


@app.route('/result2', methods=['POST', 'GET'])
def result():
    """配置IP-url"""
    job_id = 'api_job'
    if request.method == 'POST':

        job = cache.get(job_id) or {}
        if job.get('progress') in ('进行中',):
            return '任务进行中...'

        config_ = request.form
        address = config_.get('address', '')
        ID = config_.get('ID', '')
        times = int(config_.get('times', '1'))
        ip_pool = config_.get('ip_pool', '')

        line = {
            'job_id': job_id,
            'address': address,
            'ip_pool': ip_pool,
            'ID': ID,
            'times': times,
            'progress': '初始化',
            'total': 0,
            'count': 0,
            'detail': []
        }
        if ip_pool:
            cache.set('ip_pool', ip_pool, 0)

        cache.set(job_id, line, 0)
        pool.submit(run_like, url=address, aid=ID, times=times, job_id=job_id)
        return redirect(url_for('result'))

    line = cache.get(job_id) or {}
    return render_template('result2.html', result_=line)


@app.route('/metoo2', methods=['POST', 'GET'])
def metoo_():
    """配置IP-url"""
    job_id = 'api_metoo'
    if request.method == 'POST':

        job = cache.get(job_id) or {}
        if job.get('progress') in ('进行中',):
            return '任务进行中...'

        config_ = request.form
        address = config_.get('address', '')
        ID = config_.get('ID', '')
        times = int(config_.get('times', '1'))
        ip_pool = config_.get('ip_pool', '')

        line = {
            'job_id': job_id,
            'address': address,
            'ip_pool': ip_pool,
            'ID': ID,
            'times': times,
            'progress': '初始化',
            'total': 0,
            'count': 0,
            'detail': []
        }
        if ip_pool:
            cache.set('ip_pool', ip_pool, 0)

        cache.set(job_id, line, 0)
        pool.submit(run_metoo, url=address, aid=ID, times=times, job_id=job_id)
        return redirect(url_for('metoo_'))

    line = cache.get(job_id) or {}
    return render_template('metoo2.html', result_=line)


app.run(host='0.0.0.0', port=39999, debug=True)
